package ywpt.service.system;

import java.util.HashSet;
import java.util.List;

import ywpt.components.acegi.domain.Role;
import ywpt.components.acegi.domain.User;
import ywpt.core.dao.HibernateEntityDao;
import ywpt.core.exception.BusinessException;
import ywpt.core.exception.UniqueConstraintException;
import ywpt.model.PeopleInfo;


import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.directwebremoting.annotations.RemoteMethod;  
import org.directwebremoting.annotations.RemoteProxy;

/**
 * 
 * 用户服务实现类 2007-10-8 下午09:57:23
 * 
 * @author <a href="mailto:mrwyxster@gmail.com">Oliver Wen</a>
 * 
 */
@Service("userService")
@RemoteProxy(name="userService")
public class UserServiceImpl extends HibernateEntityDao<User> implements UserService {
	public UserServiceImpl() {
	}

	public User getUserById(Long id) {
		return this.get(id);
	}

	public List<User> getAllUsers() {
		return this.getAll();
	}

	@SuppressWarnings("unchecked")
	public List<User> getUsers(DetachedCriteria query) {
		return this.findAllByCriteria(query);
	}

	@SuppressWarnings("unchecked")
	public List<User> getUsers(DetachedCriteria query, int pageSize, int startIndex) {
		return this.findAllByCriteria(query, pageSize, startIndex);
	}

	public int getUsersCount(DetachedCriteria query) {
		return this.getCountByCriteria(query);
	}

	public void saveUser(User user,List<String> roles,Long peopleId) {
		User _user=setRoles(user,roles);
		try {
			if(peopleId!=null){
				PeopleInfo people = this.get(PeopleInfo.class, peopleId);
				_user.setPeople(people);
				_user.setFullName(people.getPeopleName());
			}			
			user.setUsername(_user.getUsername().toLowerCase());
			this.save(_user);
		} catch (DataIntegrityViolationException e) {
			e.printStackTrace();
			throw new UniqueConstraintException("User '" + user.getUsername() + "' already exists!");
		}
	}
	
	@SuppressWarnings("unchecked")
	public User loadUserByUsername(String username) throws BusinessException {
		User user = findUniqueBy("username", username);
		if (user == null) {
			logger.warn("uh oh, user not found...");
			throw new BusinessException("user '" + username + "' not found...");
		}
		return user;
	}
	
	@SuppressWarnings("unchecked")
	public User verifyUser(String username,String password) throws BusinessException {
		User user = findUniqueBy("username", username);
		
		if (user == null) {
			logger.warn("uh oh, user not found...");
			throw new BusinessException("user '" + username + "' not found...");
		}
		if (  ! (user.getPassword().equals(password) )  ) {
			logger.warn("uh oh, password  is not correct...");
			throw new BusinessException("user '" + username + "'password  is not correct ...");
		}		
		
		
		return user;
	}	
	
	public void updateUser(User user,List<String> roles,Long peopleId) {
		User _user=setRoles(user,roles);
		try {
			if(peopleId!=null){
				PeopleInfo people = this.get(PeopleInfo.class, peopleId);
				_user.setPeople(people);
				_user.setFullName(people.getPeopleName());
			}
			user.setUsername(_user.getUsername().toLowerCase());
			this.update(_user);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public User setRoles(User user, List<String> roles) {
		if (user != null && roles != null) {
			user.setRoles(new HashSet<Role>(0));
			//for (int i = 0, j = roles.size(); i < j; i++) {
			for (int i = 0;i<roles.size();i++) {
				Role role = super.get(Role.class, new Long(roles.get(i)));
				user.addRole(role);
				role.addUser(user);
			}
		}
		return user;
	}

	public User setRoles(Long id, List<String> roles) {
		return setRoles((User) get(id), roles);
	}

	public void removeUser(Long id) {
		this.removeById(new Long(id));
	}

	public User getUserByUsername(String username) {
		return this.findUniqueBy("username", username);
	}
	
	public int[] removeUsers(Long[] ids) {
		String hql = "delete ywpt.components.acegi.domain.User u where u.id =?";
		int results[] = new int[ids.length];
		for (int i = 0; i < ids.length; i++) {
			results[i] = super.bulkUpdate(hql, ids[i]);
		}
		return results;
	}



	public boolean checkPassword(String username, String oldPassword) {
		User user = super.findUniqueBy("username", username);
		if (user.getPassword().equalsIgnoreCase(oldPassword)) {
			return true;
		} else {
			return false;
		}
	}

	public void updatePassword(String username, String newPassword) {
		User user = super.findUniqueBy("username", username);
		try {
			user.setPassword(newPassword);
			user.setConfirmPassword(newPassword);
			this.save(user);
		} catch (BusinessException e) {
			throw new BusinessException("更新用户:'" + user.getUsername() + "'密码时出现错误!");
		}
	}

	@Override
	@RemoteMethod	
	public boolean checkUserItem(String value, String name) {
		// TODO Auto-generated method stub
		DetachedCriteria query = DetachedCriteria.forClass(User.class);
		query.add(Restrictions.eq(name, value));
		int i =this.getCountByCriteria(query);
		if(i>0)//重复
		{
			return true;
		}else
		{
			return false;
		}
		
	}
	@Override
	protected void onValid(User entity) {
		//if (!isUnique(User.class,entity, "username")) {
		//	throw new UniqueConstraintException("用户登录名" + entity.getUsername() + "重复");
		//}
	}

}